<template>
  <div class="app-container">
    <div class="container">
      <div class="handle-box">
        <el-button
        size="small"
        type="success"
        @click="add">
          <i class="icon icon-tianjia"></i>&nbsp;添加权限组
        </el-button>
      </div>
      <el-table
        :data="tableData"
        border
        style="width: 100%;margin-top:10px;"
        ref="multipconstable"
        @selection-change="handleSelectionChange">
        <el-table-column prop="title" :label="metaTitle+'标识'">
        </el-table-column>
        <el-table-column prop="group_name" :label="metaTitle+'名称'">
        </el-table-column>
        <el-table-column prop="tag" label="状态">
          <template slot-scope="scope">
            <a @click="changeStatus(scope.row)" class="pointer" v-if="scope.row.title !== 'administrator'">
              <el-tag
                :type="scope.row.status === '禁用' ? 'primary' : 'success'"
                disable-transitions>
                {{scope.row.status}}
              </el-tag>
            </a>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.title !== 'administrator'">
              <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)"
                class="ml-0 mb-1">编辑</el-button>
              <el-button
                size="mini"
                type="primary"
                @click="setRoutePower(scope.row)"
                class="ml-0 mb-1">
                <!-- setPower(scope.$index, scope.row) -->
                配置权限
              </el-button>
              <el-button
                size="mini"
                type="danger"
                @click="handleDeconste(scope.$index, scope.row)"
                class="ml-0">删除</el-button>
            </div>
            <div v-else>--</div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 编辑弹出框 -->
    <el-dialog :title="metaTitle+'管理'" :visible.sync="editVisible" width="520px" :close-on-click-modal="false" :show-close="false">
      <el-form ref="form" :model="form" label-width="120px" :rules="rules" style="width:85%;margin:0 auto;" autocompconste="off">
        <el-form-item :label="metaTitle+'标记'" prop="title">
          <el-input v-model="form.title" :placeholder="metaTitle+'标记'"></el-input>
        </el-form-item>
        <el-form-item :label="metaTitle+'名称'" prop="group_name">
          <el-input v-model="form.group_name" :placeholder="metaTitle+'名称'"></el-input>
        </el-form-item>
        <el-form-item label="是否启用">
          <el-radio-group v-model="form.status">
            <el-radio label="正常" value="1"></el-radio>
            <el-radio label="禁用" value="2"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button @click="cancel('form')" size="mini">取 消</el-button>
          <el-button type="primary" @click="saveEdit('form')" size="mini">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 配置权限 -->
    <el-dialog
      title="配置权限"
      :visible.sync="powerVisible"
      width="50%"
      :close-on-click-modal="false"
      :show-close="false"
      top="50px"
      class="my-dialog">
      <el-form
        ref="form1"
        autocompconste="off"
        label-width="80px">
        <el-form-item>
          <el-tree
            :data="powerList"
            show-checkbox
            node-key="path"
            ref="tree"
            :default-checked-keys="[]"
            :default-expanded-keys="[]"
            :default-expand-all="false"
            :expand-on-click-node="true"
            :auto-expand-parent="false"
            :highlight-current="true">
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span>{{ data.title }}</span>
            </span>
          </el-tree>
        </el-form-item>
        <el-form-item>
          <el-button @click="cancelPower('form1')" size="mini">取 消</el-button>
          <el-button type="primary" @click="savePower('form1')" size="mini">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 查看权限 -->
    <el-dialog title="查看权限查看" :visible.sync="isCheck" width="30%" >
      <el-tag type="danger" v-for="(item,index) in powerList" :key="index" class="mt-10 mr-10">{{item.title}}</el-tag>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="isCheck=false;">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 删除提示框 -->
    <el-dialog title="提示" :visible.sync="delVisible" width="300px" center>
      <div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="delVisible = false;">取 消</el-button>
        <el-button type="primary" @click="deconsteRow">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { list, put, edit, save, power, del, powers } from '@/api/group'
import { mapGetters } from 'vuex'
import { deepClone } from '@/utils'
import path from 'path'

export default {
  data() {
    var validate = (rule, value, callback) => {
      if (!this.selectedList.length && this.powerVisible) {
        callback(new Error('请选择可操作模块'))
        return
      }
      callback()
    }
    return {
      tableData: [],
      delList: [],
      editVisible: false,
      delVisible: false,
      isDelAll: false,
      powerVisible: false,
      selectModule: [],
      selectedList: [],
      powerList: [],
      isCheck: false,
      row: [],
      form: {
        id: 0,
        group_name: '',
        title: '',
        status: '正常'
      },
      rules: {
        group_name: [{ required: true, message: '请输入权限组名称', trigger: 'blur' }],
        title: [{ required: true, message: '请输入权限组标记', trigger: 'blur' }]
      },
      form1: {
        id: 0,
        title: '',
        power: ''
      },
      rules1: {
        power: [{ validator: validate, trigger: 'change' }]
      },
      defaultProps: { children: 'children', label: 'label' },
      selected: 0,
      checkedKeys: [],
      serviceRoutes: [],
      rolesList: []
    }
  },
  created() {
    this.getData()
    this.merge()
  },
  computed: {
    ...mapGetters([
      'permission_routers',
      'const_routes'
    ]),
    metaTitle() {
      return this.$route.meta.title
    },
    metaIcon() {
      return ''
    }
  },
  methods: {
    merge() {
      for (const item of this.permission_routers) {
        const flag = item.hidden || false
        if (flag) {
          continue
        } else {
          if (item.path.indexOf('*') > -1 || item.path === '/') {
            continue
          }
          const tmp = { ...item }
          const obj = {
            path: tmp.path,
            title: tmp.meta.title,
            children: [],
            model: `${tmp.path}`,
            level: 1
          }
          if (tmp.children) {
            for (const item1 of tmp.children) {
              if (item1.meta.activeMenu) {
                continue
              }
              obj.children.push({
                path: `${item.path}/${item1.path}`,
                title: item1.meta.title,
                children: [],
                model: `${tmp.path}-${item1.path}`,
                level: 2
              })
            }
          }
          this.powerList.push(obj)
        }
      }
      this.serviceRoutes = this.powerList
    },
    setRoutePower(item) {
      this.selected = item.id
      this.$store.commit('SHOW_LOADING')
      powers(item.id).then(({ status, data }) => {
        const { leader } = data
        this.$store.commit('HIDE_LOADING')
        if (status) {
          this.checkedKeys = leader ? (leader.leader1 ? JSON.parse(leader.leader1) : []) : []
          // console.log('is_checked', this.checkedKeys)
          this.powerVisible = true
          this.$nextTick(() => {
            this.$refs.tree.setCheckedKeys(this.checkedKeys)
          })
        }
      })
    },
    getData() {
      this.$store.commit('SHOW_LOADING')
      list().then(res => {
        this.$store.commit('HIDE_LOADING')
        if (res.status) {
          this.tableData = res.data.data
        }
      })
    },
    changeStatus(scope) {
      const status = scope.status === '正常' ? 0 : 1
      this.$store.commit('SHOW_LOADING')
      put(scope.id, status).then(res => {
        this.$store.commit('HIDE_LOADING')
        if (!res.status) {
          this.$message.error(res.msg)
          return
        }
        this.getData()
      })
    },
    search() {
      this.getData()
    },
    handleEdit(index, row) {
      this.$store.commit('SHOW_LOADING')
      edit(row.id).then(res => {
        this.$store.commit('HIDE_LOADING')
        if (!res.status) {
          this.$message.error(res.msg)
          return
        }
        const data = res.data
        if (data.type === 6) {
          this.isRedirect = true
          this.last_url = data.url
        }
        this.form = {
          id: data.id,
          group_name: data.group_name,
          title: data.title,
          status: data.status
        }
        this.editVisible = true
      })
    },
    handleDeconste(index, row) {
      this.idx = index
      this.row = row
      this.delVisible = true
    },
    delAll() {
      if (!this.delList.length) {
        this.$message.error('至少选择一条数据')
        return
      }
      this.isDelAll = true
      this.delVisible = true
    },
    handleSelectionChange(val) {
      val.forEach(item => {
        this.delList.push(item.id)
      })
    },
    generateTree(routes, basePath = '/', checkedKeys) {
      const res = []
      for (const route of routes) {
        const routePath = path.resolve(basePath, route.path)
        if (route.children) {
          route.children = this.generateTree(route.children, routePath, checkedKeys)
        }
        if (checkedKeys.includes(routePath) || (route.children && route.children.length >= 1)) {
          res.push(route)
        }
      }
      return res
    },
    // 保存编辑
    saveEdit(formName) {
      this.$refs[formName].validate(valid => {
        if (!valid) {
          return false
        }
        this.editVisible = false
        this.$store.commit('SHOW_LOADING')
        this.form.status = this.form.status === '正常' ? 1 : 0
        save(this.form).then(res => {
          this.$store.commit('HIDE_LOADING')
          if (!res.status) {
            this.$message.error(res.msg)
            return
          }
          this.$message.success(res.msg)
          this.$refs[formName].resetFields()
          this.getData()
        })
      })
    },
    cancelPower() {
      this.powerVisible = false
      // location.reload()
    },
    savePower(formName) {
      const checkedKeys = this.$refs.tree.getCheckedKeys()
      // console.log('is_selected', checkedKeys)
      const router = this.generateTree(deepClone(this.serviceRoutes), '/', checkedKeys)
      const json = JSON.stringify(router)
      const parent = []
      const _json = []
      for (const item of router) {
        if (item.level === 1) {
          parent.push(item.path)
        }
        if (item.children.length > 0) {
          const child = item.children
          for (const item1 of child) {
            _json.push(item1.path)
          }
        } else {
          _json.push(item.path)
        }
      }
      for (const item of router) {
        if (item.level === 2 && item.model.indexOf('-') > -1) {
          const tmp = item.model.split('-')
          if (!parent.includes(tmp[0])) {
            for (const iterator of this.permission_routers) {
              if (iterator.path === tmp[0]) {
                _json.push(iterator.path)
              }
            }
          }
        }
      }
      this.powerVisible = false
      this.$store.commit('SHOW_LOADING')
      power({
        id: this.selected,
        power: json,
        leader: JSON.stringify(checkedKeys)
      }).then(({ status, data }) => {
        this.$store.commit('HIDE_LOADING')
        if (status) {
          this.$message.success('操作成功')
          setTimeout(_ => {
            location.reload()
          }, 2e3)
        }
      })
    },
    // 确定删除
    deconsteRow() {
      this.$store.commit('SHOW_LOADING')
      if (!this.isDelAll) {
        del(this.row.id).then(res => {
          this.$store.commit('HIDE_LOADING')
          if (!res.status) {
            this.$message.error(res.msg)
            return
          }
          this.tableData.splice(this.idx, 1)
          this.$message.success(res.msg)
        })
      } else {
        del(this.delList.join('_')).then(res => {
          this.$store.commit('HIDE_LOADING')
          if (!res.status) {
            this.$message.error(res.msg)
            return
          }
          this.delList = []
          this.getData()
          this.$message.success(res.msg)
        })
      }
      this.delVisible = false
    },
    add() {
      this.form.id = 0
      this.form.group_name = ''
      this.form.status = '正常'
      this.editVisible = true
    },
    cancel(formName) {
      this.$refs[formName].resetFields()
      this.form.id = 0
      this.editVisible = false
    },
    checkPower(index, scope) {
      // if (!scope) {
      //   this.$message.error('没有配置权限')
      //   return
      // }
      // check(scope).then(res => {
      //   if (!res.status) {
      //     return
      //   }
      //   this.powerList = res.data
      //   this.isCheck = true
      // })
    },
    setPower(index, scope) {
      this.form1.id = scope.id
      this.form1.title = scope.title
      this.powerVisible = true
    },
    handleChange(value, direction, movedKeys) {
      // console.log(value, direction, movedKeys)
      if (direction === 'right') {
        // this.selectedList = value
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
